//
// Created by sgyt on 2020/3/24.
// 共享内存发送
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include "shmdata.h"

int main(int argc,char *argv[])
{
    int shmId,res;
    struct shared_use_st *data;
    //共享内存
    void *shm = NULL;
    char buffer[BUFSIZ+1];

    //创建内存共享区
    shmId = shmget((key_t)1234,sizeof(struct shared_use_st),IPC_CREAT|0666);
    if(shmId == (void *)-1)
    {
        perror("shmget is error\n");
        exit(EXIT_FAILURE);
    }

    //绑定内存共享区
    shm = shmat(shmId,0,0);

    printf("Memory attached at %X\n", (int)shm);    //设置共享内存
    data = (struct shared_use_st*)shm;


    while(1)
    {
        if(data ->write == 1)
        {
            sleep(1);
            printf("waiting ....\n");
        }
        printf("Enter some text:");
        fflush(stdout);
        fgets(buffer,BUFSIZ,stdin);
        strncpy(data->text,buffer,TEXT_SZ);
        data->write = 1;
        if(strncmp(buffer,"end",3) == 0)
        {
            break;
        }
    }


    //解除绑定共享区
    shmdt(shm);

    //删除共享区
    shmctl(shmId,IPC_RMID,0);
    return 0;
}

